<?php
/**
 * Created by PhpStorm.
 * Script Name: WsClient.php
 * Create: 2024/12/28 下午9:39
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace process;

use Workerman\Connection\AsyncTcpConnection;
use Workerman\Worker;

class WsClient
{
    private array $connectionList = [];
    /**
     * @var array
     */
    private array $wsList;

    public function __construct()
    {
        $this->connectionList = [];
        $this->wsList = [
            ['id' => 1,'host' => 'ws://47.96.139.114:4200', 'url' => "https://live.douyin.com/225086157996"]
        ];
    }

    public function onWorkerStart()
    {
        foreach ($this->wsList as $ws){
            $con = new AsyncTcpConnection($ws['host']);

            // websocket握手成功后
            $con->onWebSocketConnect = function(AsyncTcpConnection $con) use ($ws) {
                echo 'Connect success!';
                if(!isset($this->connectionList[$ws['id']])){
                    $this->connectionList[$ws['id']] = $con;
                }
                $con->send('{"url":"'.$ws['url'].'"}');
            };

            // 当收到消息时
            $con->onMessage = function(AsyncTcpConnection $con, $data) use ($ws) {
                echo $data;
            };

            $con->onClose = function (AsyncTcpConnection $con) use ($ws){
                unset($this->connectionList[$ws['id']]);
                echo "Closed!";
            };

            //$con->connect();
        }
    }
}